#!/usr/bin/python

'''
Serial format:
    * Enter Command mode : 0xfe
    (Send two bytes to set the PWM value of one of the valves.
        Address 0 maps to OCR1A, PB1, 'l'
        Address 1 maps to OCR1B, PB2, 'r')
    * First byte : 0b xxxx yyyy {Channel data, Most significant four bits of 12-bit PWM data}
    * Second byte: 0b yyyy yyyy {Least significant 8-bits of PWM value}
    (Repeat procedure for setting the PWM value for the second channel, or exit command mode.)
    *Exit command mode : 0xff
'''
import serial

class Port(serial.Serial):
    def __init__(self,*args,**kwargs):
        serial.Serial.__init__(self,*args,**kwargs)

    def wrby(self,byte):
        self.write(chr(byte))

    def reby(self):
        ret = self.read()
        if (ret  == ""):
            return None
        else:
            return ord(ret)

    def echo(self):
        self.flushInput()
        self.wrby(0x00)
        return (self.reby() == 0xfa)

if __name__ == "__main__":
    Ser = Port("/dev/ttyUSB0",baudrate = 500000,parity = "O",timeout=1)
    Ser.echo()
    Ser.wrby(0xff)
    l = Ser.reby()
    h = Ser.reby()
    byte = (h << 8) | l
    print byte - 2**16

